<?php
namespace app\api\controller\xiservice;

use app\common\controller\xiservice\XiserviceApi;
use app\common\model\xiservice\Address as AddressModel;
use app\common\model\xiservice\Area;
use think\Exception;
use think\Db;
/**
 * 地址模块
 */
class Address extends XiserviceApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model=new \app\common\model\xiservice\Address();
    }


    /**
     * @ApiTitle (用户地址列表)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.address/list)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'id':'int','name':'string','phone':'string','province_text':'string','city_text':'string','area_text':'string','addr_detail':'string'}", description="返回数据")
     */
    public function list() {
       
        $list = AddressModel::where('user_id',$this->auth->id)
                ->select();
        $this->success('查询成功',$list);
    }

    /**
     * @ApiTitle (用户地址详细)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.address/detail)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams   (name="name", type="string", description="姓名")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'id':'int','name':'string','phone':'string','province_text':'string','city_text':'string','area_text':'string','addr_detail':'string'}", description="返回数据")
     */
    public function detail() {
        $id = $this->request->request('id'); 
        $data = AddressModel::where('user_id',$this->auth->id)
                ->where('id',$id)
                ->find();
        $this->success('查询成功',$data);
    }

     /**
     * @ApiTitle (小程序:添加/编辑地址操作)
     * @ApiMethod (Post)
     * @ApiRoute (/api/xiservice.address/edit)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams   (name="id", type="integer", description="地址id")
     * @ApiParams   (name="name", type="string", description="姓名")
     * @ApiParams   (name="phone", type="string", description="手机号码")
     * @ApiParams   (name="addr", type="string", description="服务地址")
     * @ApiParams   (name="addr_detail", type="string", description="详细地址")
     * @ApiParams   (name="is_default", type="integer", description="默认地址 1=默认 0=不默认")
     * @ApiParams   (name="lat", type="float", description="定位纬度信息")
     * @ApiParams   (name="lng", type="float", description="定位经度信息")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="integer", description="返回数据")
     */
    public function edit() {
        $param=$this->request->post('','','trim,strip_tags');
        $param['user_id']=$this->auth->id;
        $lat = $this->request->request('lat'); 
        $lng = $this->request->request('lng');  

        $count = $this->model->where('user_id',$param['user_id'])->count();
        if($count>=20){
            $this->error('提交失败!最多创建20个地址!');
        }
        $areaInfo =Area::where('level',3)->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - ".$param['lat']." * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(".$param['lat']." * pi() / 180) * pow(sin((lng * pi() / 180 - ".$param['lng']." * pi() / 180) / 2),2))) * 1000) as distance")
                        ->order('distance asc')
                        ->find();
        $res = false;
        Db::startTrans();
        try {  

            if($areaInfo){
                $provinceInfo = Area::where('id',$areaInfo['pid'])->find();
                if($provinceInfo){
                    $param['province_id'] = $provinceInfo['pid'];
                }
                $param['city_id'] = $areaInfo['pid'];
                $param['area_id'] = $areaInfo['id'];
            }
            $is_default =false;
            if($param['is_default']=='true')
            {
                $is_default =true;
            }
            if($param['is_default']=='true'){
                // 把该用户其他的数据设为非默认
                $this->model->where('user_id',$param['user_id'])->where('is_default',true)->update(['is_default'=>false]);
            }
            $param['is_default']= $is_default;
            if(isset($param['id'])&&$param['id']>0){
                $id=$param['id'];
                unset($param['id']);
                $res = $this->model->allowField(true)->save($param,['id'=>$id]);
            }else{

                $res = $this->model->allowField(true)->save($param);
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        if(!$res){
            $this->error('提交失败');
        }
        $this->success('提交成功');        
        
    }  

     /**
     * @ApiTitle (删除地址)
     * @ApiMethod (Post)
     * @ApiRoute (/api/xiservice.address/del)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams   (name="id", type="integer", description="地址id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="integer", description="返回数据")
     */
    public function del(){
        $id=$this->request->request('id',0);
        $data = $this->model->where('user_id',$this->auth->id)->find($id);
        if(!$data){
            $this->error('查询不到该数据');
        }
        $res = $data->delete();
        if(!$res){
            $this->error('提交失败');
        }
        $this->success('删除成功');
    }    

}